package com.changgou.search.controller;


import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap,Model model){
        //特殊符号处理
        this.headleSearch(searchMap);

        Map resultMap = searchService.search(searchMap);

        model.addAttribute("resultMap",resultMap);
        model.addAttribute("searchMap",searchMap);

        //封装分页数据并返回
        //第一个参数 总记录数  第二个参数 当前页 第三个参数 每页显示的记录数
        Page<SkuInfo> page =new Page<SkuInfo>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),
                Page.pageSize
        );
        model.addAttribute("page",page);

        //拼装url
        StringBuilder url =new StringBuilder("/search/list");
        if(searchMap!=null&&searchMap.size()>0){
            //有搜索条件
            url.append("?");
            for (String urlString : searchMap.keySet()) {
                if(!"sortField".equals(urlString)&&!"sortRule".equals(urlString)&&!"pageNum".equals(urlString)){
                    url.append(urlString).append("=").append(searchMap.get(urlString)).append("&");
                }
            }
            String searchUrl = url.toString();
            searchUrl=searchUrl.substring(0,searchUrl.length()-1);

            model.addAttribute("url",searchUrl);
        }else {
            //没有查询条件
            model.addAttribute("url",url);
        }
        return "search";
    }

    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap){
        //特殊符号进行处理
        this.headleSearch(searchMap);

        Map searchResult = searchService.search(searchMap);
        return searchResult;
    }

    private void headleSearch(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if(entry.getKey().startsWith("spec_")){
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }
}
